﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PSDLib.Models;
using PSDLib.Ctrl;
using PSDLib;
using PSDLib.Protocols;
using System.Net;
using System.Threading;
using PSDManager.SystemSettings;

namespace PSDManager
{
    public partial class DownloadingFilesPanel : UserControl, IDataPanel
    {
        private delegate void UpdateListEventHandler(List<dl_files> files);
        private UpdateListEventHandler updateList;
        private Thread psdThread;
        private bool requesting = false;
        public dl_task Task { get; set; }
        public dl_task_channel Channel { get; set; }

        public ManagerHelper ManagerHelper { get; set; }

        public string Summary
        {
            get { return this.lblSummary.Text; }
            set { this.lblSummary.Text = value; }
        }

        public DownloadingFilesPanel()
        {
            InitializeComponent();

            updateList = new UpdateListEventHandler(UpdateDownloadingFiles);

            Summary = "共 0 个文件正在下载";

        }

        public void Reset(bool immediate = true)
        {
            if (immediate)
            {
                Task = null;
                Channel = null;
                Summary = "共 0 个文件正在下载";
                palDownloadList.Controls.Clear();
                palDownloadList.BackgroundImage = Properties.Resources.bg;
            }
        }

        public void RefreshData(params object[] parameter)
        {
            if (parameter.Length > 2)
            {
                Task = (dl_task)parameter[0];

                if (psdThread == null)
                {
                    requesting = true;
                    psdThread = new Thread(new ThreadStart(RequestPSDDownloading));
                    psdThread.Start();
                }
            }
        }

        private void RequestPSDDownloading()
        {
            while (true)
            {
                try
                {
                    if (Task != null && requesting)
                    {
                        var ds = ManagerHelper.GetOnlinePSDState(Task.download_device_id);

                        if (ds != null)
                        {
                            var msg = new RequestPSDDownloadingFilesMessage();
                            //msg.ManagerIP = ManagerHelper.ManagerEP.Address.ToString();
                            msg.ManagerPort = AppSettings.Setting.PDMListenPort;

                            var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);

                            ManagerHelper.TcpManager.Send(deviceEP, msg);
                        }
                    }

                    Thread.Sleep(5000);
                }
                catch (Exception ex)
                { }
            }
        }

        public void UpdateDataPanel(List<dl_files> files)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(updateList, files);
            }
            else
            {
                updateList(files);
            }
        }

        private void UpdateDownloadingFiles(List<dl_files> files)
        {
            try
            {
                for (int i = palDownloadList.Controls.Count - 1; i >= 0; i--)
                {
                    if (files.Where(t => ("progress_" + t.id) == palDownloadList.Controls[i].Name).FirstOrDefault() == null)
                    {
                        palDownloadList.Controls[i].Dispose();
                        //palDownloadList.Controls.RemoveAt(i);
                    }
                }

                for (int i = 0; i < files.Count; i++)
                {
                    var ctrl = palDownloadList.Controls.Find("progress_" + files[i].id, false);
                    DownloadProgress pro;

                    if (ctrl.Length == 0)
                    {
                        pro = new DownloadProgress();
                        pro.Dock = DockStyle.Top;
                        pro.Name = "progress_" + files[i].id;
                        pro.progressBar1.Minimum = 0;
                        pro.progressBar1.Maximum = 100;
                        palDownloadList.Controls.Add(pro);
                        pro.BringToFront();
                    }
                    else
                    {
                        pro = (DownloadProgress)ctrl[0];
                    }

                    pro.SuspendLayout();
                    var dt = ManagerHelper.DownloadTaskList.Where(t => t.Task.id == files[i].dl_task_id).FirstOrDefault();
                    pro.lblTaskName.Text = (dt == null ? "" : dt.Task.task_name);
                    pro.lblRoomNum.Text = files[i].room_num + " - " + files[i].channel_name;
                    pro.lblTime.Text = files[i].video_start_time.ToString("yyyy-MM-dd HH:mm:ss") + " 至 " + files[i].video_end_time.ToString("yyyy-MM-dd HH:mm:ss");
                    pro.progressBar1.Value = files[i].dl_progress;
                    pro.lblSpeed.Text = PSDFunction.FormatByteSize(Convert.ToDouble(files[i].dl_speed)) + "/s";
                    double time = (DateTime.Now - files[i].dl_start_time.Value).TotalSeconds;
                    pro.lblSpeed.Text += "，已用时 " + (time < 0 ? "0" : time.ToString("0")) + " 秒";
                    pro.lblPercent.Text = "已下载 " + files[i].dl_progress.ToString() + "%";
                    pro.ResumeLayout();
                }

                Summary = "共 " + palDownloadList.Controls.Count + " 个文件正在下载";

                if (palDownloadList.Controls.Count == 0)
                {
                    this.palDownloadList.BackgroundImage = Properties.Resources.bg;
                }
                else
                {
                    this.palDownloadList.BackgroundImage = null;
                }
            }
            catch (Exception ex)
            {
            }
        }

    }
}
